#include "ChatServer.hpp"
#include "InetAddr.hpp"
#include "Route.hpp"
#include "ThreadPool_singleton.hpp"
#include <memory>

void Usage(std::string proc) // 使用手册
{
    std::cout << "Usage: " << proc << " serverip serverport" << std::endl;
}

// Debug
// void Chat(int sockfd, const std::string message, InetAddr addr)
// {
//     LOG(LogLevel::DEBUG) << "sockfd: " << sockfd;
//     LOG(LogLevel::DEBUG) << "message: " << message;
//     LOG(LogLevel::DEBUG) << "client addr: " << addr.ToString();

//     // 写回发送方
//      sendto(sockfd, message.c_str(), sizeof(message), 0, addr.Addr(), addr.Length());
// }
using task_t = std::function<void()>;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    Console();
    uint16_t port = std::stoi(argv[1]);
    // std::unique_ptr<ChatServer> us = std::make_unique<ChatServer>(port, Chat);

    //消息转发功能
    std::unique_ptr<Route> r = std::make_unique<Route>();

    //线程池对象
    auto tp = ThreadPool<task_t>::GetInstance();

    //服务器对象
    //要将路由任务push到线程池对象中，所以匿名函数就要关联两个对象
    std::unique_ptr<ChatServer> us = std::make_unique<ChatServer>(port, 
        [&r, &tp](int sockfd, std::string message, InetAddr addr)
        {
            //将两个任务绑定为一个任务:路由任务和服务器回调
            task_t task = std::bind(&Route::RouteMessageToAll, r.get(), sockfd, message, addr);
            tp->Push(task);//入队列
        }
    );

    us->Init();
    us->Start();
    return 0;
}